<template>
  <div class="registration-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">报名管理</h1>
        <p class="page-subtitle">管理所有活动的报名申请</p>
      </div>
      <div class="header-actions">
        <el-button @click="exportRegistrations">
          <el-icon><Download /></el-icon>
          导出数据
        </el-button>
        <el-button type="primary" @click="batchApprove" :disabled="selectedRegistrations.length === 0">
          <el-icon><Check /></el-icon>
          批量通过
        </el-button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :xs="12" :sm="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-number">{{ stats.total }}</div>
            <div class="stat-label">总报名</div>
          </div>
          <el-icon class="stat-icon"><Tickets /></el-icon>
        </el-card>
      </el-col>
      <el-col :xs="12" :sm="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-number">{{ stats.pending }}</div>
            <div class="stat-label">待审核</div>
          </div>
          <el-icon class="stat-icon pending"><Clock /></el-icon>
        </el-card>
      </el-col>
      <el-col :xs="12" :sm="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-number">{{ stats.approved }}</div>
            <div class="stat-label">已通过</div>
          </div>
          <el-icon class="stat-icon approved"><Check /></el-icon>
        </el-card>
      </el-col>
      <el-col :xs="12" :sm="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-number">{{ stats.rejected }}</div>
            <div class="stat-label">已拒绝</div>
          </div>
          <el-icon class="stat-icon rejected"><Close /></el-icon>
        </el-card>
      </el-col>
    </el-row>

    <!-- 搜索和筛选 -->
    <el-card class="filter-card">
      <el-form :model="filters" inline class="filter-form">
        <el-form-item label="关键词">
          <el-input
            v-model="filters.keyword"
            placeholder="搜索学生姓名或学号"
            clearable
            style="width: 200px"
            @keyup.enter="loadRegistrations"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        
        <el-form-item label="活动">
          <el-select v-model="filters.activityId" placeholder="选择活动" clearable style="width: 200px">
            <el-option label="全部活动" value="" />
            <el-option 
              v-for="activity in activities" 
              :key="activity.id" 
              :label="activity.title" 
              :value="activity.id" 
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="状态">
          <el-select v-model="filters.status" placeholder="选择状态" clearable style="width: 150px">
            <el-option label="全部" value="" />
            <el-option label="待审核" value="pending" />
            <el-option label="已通过" value="approved" />
            <el-option label="已拒绝" value="rejected" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="报名时间">
          <el-date-picker
            v-model="filters.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="loadRegistrations">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetFilters">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 报名列表 -->
    <el-card class="list-card">
      <template #header>
        <div class="list-header">
          <div class="header-title">
            <span>报名列表</span>
            <el-tag v-if="pagination.total > 0" type="info" size="small">
              共 {{ pagination.total }} 条报名
            </el-tag>
          </div>
          <div class="header-actions">
            <el-checkbox 
              v-model="selectAll" 
              :indeterminate="isIndeterminate"
              @change="handleSelectAll"
            >
              全选
            </el-checkbox>
          </div>
        </div>
      </template>
      
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="5" animated />
      </div>
      
      <!-- 空状态 -->
      <div v-else-if="registrations.length === 0" class="empty-container">
        <el-empty description="暂无报名记录" />
      </div>
      
      <!-- 报名表格 -->
      <div v-else class="table-container">
        <el-table 
          :data="registrations" 
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          
          <el-table-column label="学生信息" min-width="200">
            <template #default="{ row }">
              <div class="student-info">
                <div class="student-name">{{ row.student?.name }}</div>
                <div class="student-details">
                  <span class="student-id">{{ row.student?.studentId }}</span>
                  <span class="student-major">{{ row.student?.major }}</span>
                </div>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column label="活动信息" min-width="200">
            <template #default="{ row }">
              <div class="activity-info">
                <div class="activity-title">{{ row.activity?.title }}</div>
                <div class="activity-time">
                  {{ formatDate(row.activity?.startTime, 'MM-DD HH:mm') }}
                </div>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.status)" size="small">
                {{ getStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="applyTime" label="报名时间" width="150">
            <template #default="{ row }">
              {{ formatDate(row.applyTime, 'MM-DD HH:mm') }}
            </template>
          </el-table-column>
          
          <el-table-column label="联系方式" width="120">
            <template #default="{ row }">
              <div class="contact-info">
                <div v-if="row.student?.phone" class="contact-item">
                  <el-icon><Phone /></el-icon>
                  <span>{{ row.student.phone }}</span>
                </div>
                <div v-if="row.student?.email" class="contact-item">
                  <el-icon><Message /></el-icon>
                  <span>{{ row.student.email }}</span>
                </div>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column label="备注" width="150" show-overflow-tooltip>
            <template #default="{ row }">
              {{ row.remark || '-' }}
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" size="small" text @click="viewRegistration(row)">
                查看
              </el-button>
              <el-button 
                v-if="row.status === 'pending'"
                type="success" 
                size="small" 
                text 
                @click="approveRegistration(row.id)"
              >
                通过
              </el-button>
              <el-button 
                v-if="row.status === 'pending'"
                type="danger" 
                size="small" 
                text 
                @click="rejectRegistration(row.id)"
              >
                拒绝
              </el-button>
              <el-button 
                v-if="row.status === 'approved'"
                type="warning" 
                size="small" 
                text 
                @click="cancelRegistration(row.id)"
              >
                取消
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <!-- 分页 -->
      <div v-if="registrations.length > 0" class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="loadRegistrations"
          @current-change="loadRegistrations"
        />
      </div>
    </el-card>

    <!-- 查看报名详情对话框 -->
    <el-dialog 
      v-model="detailDialogVisible" 
      title="报名详情" 
      width="600px"
      :before-close="closeDetailDialog"
    >
      <div v-if="currentRegistration" class="registration-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="学生姓名">
            {{ currentRegistration.student?.name }}
          </el-descriptions-item>
          <el-descriptions-item label="学号">
            {{ currentRegistration.student?.studentId }}
          </el-descriptions-item>
          <el-descriptions-item label="专业">
            {{ currentRegistration.student?.major }}
          </el-descriptions-item>
          <el-descriptions-item label="年级">
            {{ currentRegistration.student?.grade }}
          </el-descriptions-item>
          <el-descriptions-item label="联系电话">
            {{ currentRegistration.student?.phone || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="邮箱">
            {{ currentRegistration.student?.email || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="活动名称" :span="2">
            {{ currentRegistration.activity?.title }}
          </el-descriptions-item>
          <el-descriptions-item label="报名时间">
            {{ formatDate(currentRegistration.applyTime, 'YYYY-MM-DD HH:mm:ss') }}
          </el-descriptions-item>
          <el-descriptions-item label="当前状态">
            <el-tag :type="getStatusType(currentRegistration.status)">
              {{ getStatusText(currentRegistration.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item v-if="currentRegistration.approveTime" label="审核时间">
            {{ formatDate(currentRegistration.approveTime, 'YYYY-MM-DD HH:mm:ss') }}
          </el-descriptions-item>
          <el-descriptions-item v-if="currentRegistration.rejectReason" label="拒绝原因" :span="2">
            {{ currentRegistration.rejectReason }}
          </el-descriptions-item>
          <el-descriptions-item v-if="currentRegistration.remark" label="备注" :span="2">
            {{ currentRegistration.remark }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDetailDialog">关闭</el-button>
          <el-button 
            v-if="currentRegistration?.status === 'pending'"
            type="success" 
            @click="approveRegistration(currentRegistration.id)"
          >
            通过
          </el-button>
          <el-button 
            v-if="currentRegistration?.status === 'pending'"
            type="danger" 
            @click="rejectRegistration(currentRegistration.id)"
          >
            拒绝
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 拒绝报名对话框 -->
    <el-dialog 
      v-model="rejectDialogVisible" 
      title="拒绝报名" 
      width="500px"
    >
      <el-form :model="rejectForm" label-width="80px">
        <el-form-item label="拒绝原因" required>
          <el-input 
            v-model="rejectForm.reason"
            type="textarea"
            :rows="4"
            placeholder="请输入拒绝原因"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="rejectDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmReject" :loading="rejecting">
            确定拒绝
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { formatDate } from '@/utils'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '@/utils/api'
import {
  Download,
  Check,
  Tickets,
  Clock,
  Close,
  Search,
  Refresh,
  Phone,
  Message
} from '@element-plus/icons-vue'

const loading = ref(false)
const rejecting = ref(false)
const detailDialogVisible = ref(false)
const rejectDialogVisible = ref(false)
const selectAll = ref(false)

const stats = reactive({
  total: 0,
  pending: 0,
  approved: 0,
  rejected: 0
})

const filters = reactive({
  keyword: '',
  activityId: '',
  status: '',
  dateRange: null
})

const pagination = reactive({
  current: 1,
  size: 20,
  total: 0
})

const rejectForm = reactive({
  reason: ''
})

const registrations = ref([])
const activities = ref([])
const selectedRegistrations = ref([])
const currentRegistration = ref(null)
const currentRejectId = ref(null)

const isIndeterminate = computed(() => {
  const selectedCount = selectedRegistrations.value.length
  const totalCount = registrations.value.length
  return selectedCount > 0 && selectedCount < totalCount
})

const getStatusType = (status) => {
  const typeMap = {
    pending: 'warning',
    approved: 'success',
    rejected: 'danger',
    cancelled: 'info'
  }
  return typeMap[status] || ''
}

const getStatusText = (status) => {
  const textMap = {
    pending: '待审核',
    approved: '已通过',
    rejected: '已拒绝',
    cancelled: '已取消'
  }
  return textMap[status] || status
}

const loadStats = async () => {
  try {
    const response = await api.get('/organizer/registrations/stats')
    const data = response.data.data
    
    Object.assign(stats, data)
    
  } catch (error) {
    console.error('加载统计数据失败:', error)
  }
}

const loadActivities = async () => {
  try {
    const response = await api.get('/organizer/activities', {
      params: { size: 1000, status: 'published,ongoing' }
    })
    
    activities.value = response.data.data?.data || []
    
  } catch (error) {
    console.error('加载活动列表失败:', error)
  }
}

const loadRegistrations = async () => {
  try {
    loading.value = true
    
    const params = {
      page: pagination.current - 1,
      size: pagination.size,
      ...filters
    }
    
    // 处理日期范围
    if (filters.dateRange && filters.dateRange.length === 2) {
      params.startDate = filters.dateRange[0]
      params.endDate = filters.dateRange[1]
    }
    
    const response = await api.get('/organizer/registrations', { params })
    const data = response.data.data
    
    registrations.value = data.data || []
    pagination.total = data.total || 0
    
    // 重置选择状态
    selectedRegistrations.value = []
    selectAll.value = false
    
  } catch (error) {
    console.error('加载报名列表失败:', error)
    ElMessage.error('加载报名列表失败')
  } finally {
    loading.value = false
  }
}

const resetFilters = () => {
  Object.assign(filters, {
    keyword: '',
    activityId: '',
    status: '',
    dateRange: null
  })
  pagination.current = 1
  loadRegistrations()
}

const handleSelectAll = (checked) => {
  if (checked) {
    selectedRegistrations.value = registrations.value.filter(r => r.status === 'pending')
  } else {
    selectedRegistrations.value = []
  }
}

const handleSelectionChange = (selection) => {
  selectedRegistrations.value = selection.filter(r => r.status === 'pending')
  selectAll.value = selectedRegistrations.value.length === registrations.value.filter(r => r.status === 'pending').length
}

const viewRegistration = (registration) => {
  currentRegistration.value = registration
  detailDialogVisible.value = true
}

const closeDetailDialog = () => {
  detailDialogVisible.value = false
  currentRegistration.value = null
}

const approveRegistration = async (id) => {
  try {
    await api.put(`/organizer/registrations/${id}/approve`)
    
    ElMessage.success('报名已通过')
    loadRegistrations()
    loadStats()
    closeDetailDialog()
    
  } catch (error) {
    console.error('通过报名失败:', error)
    ElMessage.error('通过报名失败')
  }
}

const rejectRegistration = (id) => {
  currentRejectId.value = id
  rejectForm.reason = ''
  rejectDialogVisible.value = true
}

const confirmReject = async () => {
  if (!rejectForm.reason.trim()) {
    ElMessage.warning('请输入拒绝原因')
    return
  }
  
  try {
    rejecting.value = true
    
    await api.put(`/organizer/registrations/${currentRejectId.value}/reject`, {
      reason: rejectForm.reason
    })
    
    ElMessage.success('报名已拒绝')
    rejectDialogVisible.value = false
    loadRegistrations()
    loadStats()
    closeDetailDialog()
    
  } catch (error) {
    console.error('拒绝报名失败:', error)
    ElMessage.error('拒绝报名失败')
  } finally {
    rejecting.value = false
  }
}

const cancelRegistration = async (id) => {
  try {
    await ElMessageBox.confirm(
      '确定要取消这个报名吗？取消后学生将收到通知。',
      '取消报名',
      {
        confirmButtonText: '确定取消',
        cancelButtonText: '不取消',
        type: 'warning'
      }
    )
    
    await api.put(`/organizer/registrations/${id}/cancel`)
    
    ElMessage.success('报名已取消')
    loadRegistrations()
    loadStats()
    
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消报名失败:', error)
      ElMessage.error('取消报名失败')
    }
  }
}

const batchApprove = async () => {
  if (selectedRegistrations.value.length === 0) {
    ElMessage.warning('请选择要通过的报名')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要批量通过选中的 ${selectedRegistrations.value.length} 个报名吗？`,
      '批量通过',
      {
        confirmButtonText: '确定通过',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const ids = selectedRegistrations.value.map(r => r.id)
    await api.put('/organizer/registrations/batch-approve', { ids })
    
    ElMessage.success('批量通过成功')
    loadRegistrations()
    loadStats()
    
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量通过失败:', error)
      ElMessage.error('批量通过失败')
    }
  }
}

const exportRegistrations = () => {
  ElMessage.info('数据导出功能开发中...')
}

onMounted(() => {
  loadStats()
  loadActivities()
  loadRegistrations()
})
</script>

<style scoped>
.registration-management {
  max-width: 1400px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 24px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header-content {
  flex: 1;
}

.page-title {
  font-size: 24px;
  font-weight: 700;
  color: #303133;
  margin: 0 0 8px 0;
}

.page-subtitle {
  font-size: 14px;
  color: #606266;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 12px;
  margin-left: 20px;
}

.stats-row {
  margin-bottom: 24px;
}

.stat-card {
  height: 100px;
  cursor: pointer;
  transition: transform 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
}

.stat-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
}

.stat-number {
  font-size: 24px;
  font-weight: 700;
  color: #303133;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.stat-icon {
  font-size: 28px;
  opacity: 0.3;
  color: #409eff;
}

.stat-icon.pending {
  color: #e6a23c;
}

.stat-icon.approved {
  color: #67c23a;
}

.stat-icon.rejected {
  color: #f56c6c;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.list-card {
  min-height: 400px;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  display: flex;
  align-items: center;
  gap: 12px;
  font-weight: 600;
  color: #303133;
}

.loading-container,
.empty-container {
  padding: 40px;
  text-align: center;
}

.table-container {
  margin-bottom: 20px;
}

.student-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.student-name {
  font-weight: 600;
  color: #303133;
}

.student-details {
  display: flex;
  gap: 12px;
  font-size: 12px;
  color: #909399;
}

.activity-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.activity-title {
  font-weight: 600;
  color: #303133;
}

.activity-time {
  font-size: 12px;
  color: #909399;
}

.contact-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.contact-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #606266;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #e4e7ed;
}

.registration-detail {
  margin-bottom: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
    text-align: center;
  }
  
  .header-actions {
    margin-left: 0;
    flex-direction: column;
  }
  
  .filter-form {
    flex-direction: column;
  }
  
  .filter-form .el-form-item {
    margin-right: 0;
    margin-bottom: 16px;
  }
  
  .list-header {
    flex-direction: column;
    gap: 12px;
  }
  
  .student-details {
    flex-direction: column;
    gap: 4px;
  }
  
  .contact-info {
    gap: 2px;
  }
}
</style>